const express = require("express");
const multiparty = require('multiparty')
const fs = require("fs")
const path = require('path')


const AlbumServices =  require("../services/album-services")

const JSONResult =  require("../bean/json-result")
const {timeFormat} =  require("../utils/date-utils")
const {makeDirectory} =  require("../utils/file-utils")


const router = express.Router()
const service = new AlbumServices()


/**
 * 页面底部个人信息
 * @type {{QQ: string, phone: string, email: string}}
 */
const info = {
    phone:"18393106332",
    QQ:"1270417842",
    email:"1270417842@qq.com"
}

/**
 * 相册列表页面
 */
router.get('/album.html',async (req,res,next) =>{
    const RowsDataPackets = await service.queryAlbumList()
    console.log("RowsDataPackets:",RowsDataPackets)
    for (let i = 0,len = RowsDataPackets.length; i < len; i++) {
        const albumList = RowsDataPackets[i].album_list.split(",");
        const createTime = timeFormat(RowsDataPackets[i].create_time)
        RowsDataPackets[i].album_list = albumList[0]
        RowsDataPackets[i].create_time = createTime
    }
    res.render('blog/album.html',{title:"相册",info:info,albumList:RowsDataPackets});
})

/**
 * 上传相册页面
 */
router.get('/upload-album.html',(req,res,next) =>{
    res.render('blog/upload-album.html',{title:"上传相册",info:info});
})

/**
 * 上传相册接口
 */
router.post('/upload-album.do',(req,res,next) =>{
    const {session:{user:{userId}}} = req
    // const {title,content,description,address,albumList,createTime} = body
    console.log("==upload-album.do===进入后台文件上传接口====")
    console.log("==albumController=====upload-album.do===== req.url:", req.url)
    console.log('==albumController==upload-req.headers======', req.headers)

    const imagesUrlList = []
    const album = {
        title:"",
        content:"",
        description:"",
        address:"",
        albumList:"",
        createTime:"",
        userId:""
    }

    //获取表单的数据 以及post过来的图片
    const dateDir = new Date().toLocaleDateString().replace(/\//g,"-")
    const dir = `./public/static/album/${dateDir}/`
    let result = ""
    if (!fs.existsSync(dir)) {
        result = makeDirectory(dir)
    }
    console.log("创建文件result:",result)

    const form = new multiparty.Form({
        encoding:"utf-8",
        uploadDir:dir,               //文件上传地址
        keepExtensions:true          //保留后缀
    })
    /**
     * 写相册文件
     */
    form.parse(req,async (err,fields,files)=>{
        /**获取提交的数据以及图片上传成功返回的图片信息*/
        /**获取表单的数据*/
        console.log("上传文件表单数据fields：",fields);
        /**图片上传成功返回的信息*/
        console.log("=======上传的文件files：==========",files);

        const {title,content,description,address,createTime} = fields
        const imagesList = files.album
        console.log("imagesList:",imagesList)
        for (let i = 0,len = imagesList.length; i < len; i++) {
            let imgUrl = imagesList[i].path
            imgUrl = imgUrl.replace("public",'')
            imagesUrlList.push(imgUrl)
        }

        album.title = title
        album.content = content
        album.description = description
        album.address = address
        album.albumList = imagesUrlList.toString()
        album.createTime = timeFormat(createTime)
        album.userId = userId

        const {insertId,affectedRows} = await service.insertAlbum(album)
        console.log("album-controller ==== insertId:",insertId)
        console.log("album-controller ==== affectedRows:",affectedRows)
        //拿到的是 提交的数据 和图片 路径 保存到数据库表中
        res.send(new JSONResult({code:200,message:"上传成功",data:{id:insertId}}));
        next()
    })

})
/***
 * 上传相册：隐藏功能，页面元素隐藏了
 * PS:这是个测试功能，页面隐藏元素放开就能用
 */
router.post('/upload', (req, res) => {
    console.log('upload-req.headers---', req.headers)
    try {
        const dateDir = new Date().toLocaleDateString().replace(/\//g,"-")
        const dir = `./public/static/album/${dateDir}/`
        const form = new multiparty.Form({
            encoding: 'utf8',
            uploadDir: dir  // 用户上传文件的临时目录
        });
        form.parse(req, function(err, fields, files) {
            console.log("==============files:=============",files)
        });
        // res.redirect('http://192.168.1.81:3001/test')
    } catch (error) {
        res.end('err')
    }
})
/**
 * 更新相册
 */
router.put('/update-album.do',async (req,res,next) =>{
    const {query,params,body,path,session:{user:{userId}}} = req
    const {title,content,description,address,albumList,createTime} = body
    console.log("homeController=====upload-album.do===== req.url:", req.url)
    console.log("=======homeController=====进入后台文件上传接口================")
    //获取表单的数据 以及post过来的图片
    const dateDir = new Date().toLocaleDateString().replace(/\//g,"-")
    const form = new multiparty.Form({
        encoding:"utf-8",
        uploadDir:`./public/static/album/${dateDir}/`,  //文件上传地址
        keepExtensions:true  //保留后缀
    })
    const dir = `./public/static/album/${dateDir}/`
    if (!fs.existsSync(dir)) {
        makeDirectory(dir)
    }
    // 上传图片保存的地址     目录必须存在
    form.uploadDir = dir
    const imagesUrlList = []
    /**
     * 写相册文件
     */
    form.parse(req,(err,fields,files)=>{
        /**获取提交的数据以及图片上传成功返回的图片信息*/
        /**获取表单的数据*/
        console.log("上传文件表单数据：",fields);
        /**图片上传成功返回的信息*/
        console.log("上传的文件：",files);
        const {image} = files

        for (let i = 0,len = image.length; i < len; i++) {
            let imgUrl = image[0].path
            console.log("imgUrl:",imgUrl)
            imgUrl = imgUrl.replace("public",'')
            imagesUrlList.push(imgUrl)
        }

    })
    const album = {
        title:title,
        content:content,
        description:description,
        address:address,
        albumList:imagesUrlList.toString(),
        createTime:timeFormat(createTime),
        userId:userId
    }
    const {insertId,affectedRows} = await service.insertAlbum(album)
    console.log("album-controller ==== insertId:",insertId)
    console.log("album-controller ==== affectedRows:",affectedRows)
    // 拿到的是 提交的数据 和图片 路径 保存到数据库表中
    res.send(new JSONResult({code:200,message:"上传成功",data:{id:insertId}}));
    next()
})

/**
 * 相册详情页面
 */
router.get('/view-album.html/:albumId',async (req,res,next) =>{
    const {params:{albumId}} = req
    console.log("albumController======albumId:",albumId)
    const RowsDataPackets = await service.queryAlbumById(albumId)
    console.log("RowsDataPackets:",RowsDataPackets)
    let albumList = RowsDataPackets[0].album_list.split(",");
    for (let i = 0,len = albumList.length ; i < len; i++) {
        console.log(`image${i+1}Url:`,albumList[i])
    }
    const createTime = timeFormat(RowsDataPackets[0].create_time)
    RowsDataPackets[0].create_time = createTime
    res.render('album/view-album.html',{title:"相册详情",info:info,album:RowsDataPackets[0],albumList:albumList});
})

module.exports = router
